package com.fzhucc.modules.displayMap.service.impl;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.activity.domain.dto.ActivityUsersQueryCriteria;
import com.fzhucc.modules.appletBanner.domain.dto.AppletBannerQueryCriteria;
import com.fzhucc.modules.displayMap.domain.DisplayMap;
import com.fzhucc.modules.displayMap.domain.dto.DisplayMapAddEditDto;
import com.fzhucc.modules.displayMap.domain.dto.DisplayMapDto;
import com.fzhucc.modules.displayMap.domain.dto.DisplayMapQueryCriteria;
import com.fzhucc.modules.displayMap.domain.dto.DisplayMapTypeQueryCriteria;
import com.fzhucc.modules.displayMap.repository.DisplayMapRepository;
import com.fzhucc.modules.displayMap.service.DisplayMapService;
import com.fzhucc.modules.displayMap.service.mapstruct.DisplayMapMapper;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.notice.domain.dto.NoticeQueryCriteria;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author yyg
 * @description 服务实现
 * @date 2022-10-25
 **/
@Service
@RequiredArgsConstructor
public class DisplayMapServiceImpl implements DisplayMapService {

    private final DisplayMapRepository displayMapRepository;
    private final DisplayMapMapper displayMapMapper;

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    private final UserRepository userRepository;

    private final FenRecordLogService fenRecordLogService;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${fen.type.dt}")
    public String dt;

    @Override
    public Map<String, Object> queryAll(DisplayMapQueryCriteria criteria, Pageable pageable) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(dt);
        } catch (Exception e) {

        }

        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
                if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                    //TODO 即查询参数有参数  省总账号查具体模糊查询
                    String[] orgAreas = criteria.getOrgAreas();
                    criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
                }
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                //传参要查的 orgArea
                String csOrgArea = orgAreas[orgAreas.length - 1];
                //登录用户的 orgArea
                String dlOrgArea = criteria.getOrgArea();
                if (dlOrgArea == null) { //表示省总
                    criteria.setOrgArea(csOrgArea);
                } else {
                    //不是省总  登录的 存在  传进来的全部 则可以 否则则使用登录的
                    String[] split = dlOrgArea.split(";");
                    if (split.length == 1) {
                        //表示为省
                        if (split[0].equals(all)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            //其他省 则 传进来的第一个和这个省一致才返回数据
                            String orgArea = orgAreas[0];
                            if (split[0].equals(orgArea)) {
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 2) {
                        //例 ： 福建省;福州市;
                        String s = split[1];
                        if (orgAreas.length == 3) {
                            //福建省;福州市;马尾区;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                        if (orgAreas.length == 2) {
                            //福建省;福州市;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 3) {
                        //例 ： 福建省;福州市;马尾区;  相符就查马尾区  不相符就查登录用户的区域
                        String s = split[2];
                        if (s.equals(csOrgArea)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            criteria.setOrgArea(dlOrgArea);
                        }
                    }
                }
            }
        }
        Page<DisplayMap> page = displayMapRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<DisplayMapDto> map = page.map(displayMapMapper::toDto);
        List<DisplayMapDto> last = map.getContent();
        if (last != null && last.size() > 0) {
            for (DisplayMapDto noticeDto : last) {
                String orgArea = noticeDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    noticeDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    noticeDto.setOrgAreas(array);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看
    public String setCriteria(DisplayMapQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    @Override
    public List<DisplayMapDto> queryAll(DisplayMapQueryCriteria criteria) {
        return displayMapMapper.toDto(displayMapRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public List<DictDetailDto> findAllType(DisplayMapTypeQueryCriteria displayMapTypeQueryCriteria) {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("map_type");
        dictQueryCriteria.setOrgArea(displayMapTypeQueryCriteria.getOrgArea());
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    @Override
    @Transactional
    public DisplayMapDto findById(Integer id) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(dt);
        } catch (Exception e) {

        }

        DisplayMap displayMap = displayMapRepository.findById(id).orElseGet(DisplayMap::new);
        ValidationUtil.isNull(displayMap.getId(), "DisplayMap", "id", id);
        DisplayMapDto displayMapDto = displayMapMapper.toDto(displayMap);

        String orgArea = displayMapDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            displayMapDto.setOrgAreas(array);
        } else {
            String[] array = {};
            displayMapDto.setOrgAreas(array);
        }
        return displayMapDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DisplayMapDto create(DisplayMapAddEditDto dto) {
        DisplayMap resources = new DisplayMap();
        resources.setName(dto.getName());
        resources.setAddress(dto.getAddress());
        resources.setLongitude(dto.getLongitude());
        resources.setLatitude(dto.getLatitude());
        resources.setContract(dto.getContract());
        resources.setSort(dto.getSort());
        resources.setPhone(dto.getPhone());
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        resources.setIsShow(dto.getIsShow());
        resources.setType(dto.getType());
        return displayMapMapper.toDto(displayMapRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DisplayMapAddEditDto dto) {
        DisplayMap displayMap = displayMapRepository.findById(dto.getId()).orElseGet(DisplayMap::new);
        ValidationUtil.isNull(displayMap.getId(), "DisplayMap", "id", dto.getId());

        displayMap.setName(dto.getName());
        displayMap.setAddress(dto.getAddress());
        displayMap.setLongitude(dto.getLongitude());
        displayMap.setLatitude(dto.getLatitude());
        displayMap.setContract(dto.getContract());
        displayMap.setSort(dto.getSort());
        displayMap.setPhone(dto.getPhone());
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            displayMap.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            displayMap.setOrgArea(orgAreaReturn());
        }
        displayMap.setIsShow(dto.getIsShow());
        displayMap.setType(dto.getType());
        displayMapRepository.save(displayMap);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            displayMapRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DisplayMapDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DisplayMapDto displayMap : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("位置名(简短)", displayMap.getName());
            map.put("详细地址", displayMap.getAddress());
            map.put("经度", displayMap.getLongitude());
            map.put("纬度", displayMap.getLatitude());
            map.put("联系人", displayMap.getContract());
            map.put("联系方式", displayMap.getPhone());
            map.put("分类", displayMap.getType());
            map.put("排序", displayMap.getSort());
            map.put("是否显示默认显示", displayMap.getIsShow());
            String orgArea = displayMap.getOrgArea();
            if (orgArea != null) {
                if (orgArea.contains(";")) {
                    String[] split = orgArea.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("所属工会", str);
                } else {
                    map.put("所属工会", orgArea);
                }
            } else {
                map.put("所属工会", "");
            }
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /*@Override
    public int findCountAllType(LargeMapQueryCriteria criteria) {
        String type = criteria.getType();
        if (type == null || type.equals("")){
            return 0;
        }
        return displayMapRepository.findCountByAllType(type);
    }*/
}